package com.qy.util;


import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class WeiXinUtil {
	
	 /** 
     * <b>根据openId获取用户信息，需要认证才可以，暂时无法使用，还没有认证<b> 
     * @return String 
	 * @throws Exception 
     */  
    public static JSONObject getUserInfoByOpenId(String openId,String token,int type) throws Exception {  
        String apiUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="  
                + getAccessToken(type) + "&openid=" + openId + "&lang=zh_CN";  
        JSONObject json = null;
        try {  
            json = JSONObject.parseObject(HttpUtils.getInstance()  
                    .createPostHttpRequest(apiUrl, ""));
            json.put("accessToken", token);
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return json;
    }  
    
    /** 
     * <b>获取最新accessToken<b> 
     *  
     * @return String 
     * @throws Exception 
     */  
    public static String getAccessToken(int type) throws Exception {
    	String access_token = WeiXinContants.getAccess_token_value(getAppID(type));
    	if(access_token==null||access_token.equals("null")){
    		 String apiUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
    			+ getAppID(type)
    	                + "&secret=" + getAppSecret(type);  
    	  
    	        JSONObject json = JSONObject.parseObject(HttpUtils.getInstance()  
    	                .getJsonObjectByUrl(apiUrl));  
    	  
    	        access_token = json.get("access_token") + "";  
    	        /*
    	         * 更新token
    	         */
    	        WeiXinContants.setAccessTokenValue(getAppID(type),access_token);
    	}
       
        return access_token;  
    }  
    
    /**
     * 获取JsapiTicket
     * @return
     * @throws Exception
     */
    public static String getJsapiTicket(int type) throws Exception {
    	String jsapiTicket = WeiXinContants.getJsapiTicket();
    	if(jsapiTicket==null){
    		 String apiUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?"
    		 		+ "access_token="+getAccessToken(type)+"&type=jsapi";  
    	  
    	        JSONObject json = JSONObject.parseObject(HttpUtils.getInstance()  
    	                .getJsonObjectByUrl(apiUrl));  
    	  
    	        jsapiTicket = json.get("ticket") + "";  
    	        /*
    	         * 更新token
    	         */
    	        WeiXinContants.setJsapiTicket(jsapiTicket);
    	}
        return jsapiTicket;  
    }  
    
    /**
     * 解析微信传来的流数据
     * @param is
     * @return
     */
    public static String getInfoFromIoStream(InputStream is) {  
        String pushData = "";  
        try {  
            if (is != null) {  
                String charSet = null;  
                charSet = "utf-8";  
                byte b[] = new byte[200];  
                int numRead = is.read(b);  
                if (numRead != -1) {  
                    String content = new String(b, 0, numRead);  
                    while (numRead != -1) {  
                        numRead = is.read(b);  
                        if (numRead != -1) {  
                            String newContent = new String(b, 0, numRead,  
                                    charSet);  
                            content += newContent;  
                        }  
                    }  
                    pushData = content;  
                }  
            }  
            return pushData;  
        } catch (IOException e) {  
            return "";  
        }  
    }  
	
    /**
     * 把字符串转换成微信前端需要的格式
     * @param content
     * @param toUserName
     * @param createTime
     * @return
     * @throws Exception 
     */
	public static String getReplyConentXmlStr(String content,
			String toUserName, long createTime) throws Exception {
		String replyAguangSoftTestContentXMLStr = "<xml>"
				+ "<ToUserName><![CDATA[" + toUserName + "]]></ToUserName>"
				+ "<FromUserName><![CDATA[" + SystemParamsUtil.getWeiXinNo()
				+ "]]></FromUserName>" + "<CreateTime>" + createTime
				+ "</CreateTime>" + "<MsgType><![CDATA[text]]></MsgType>"
				+ "<Content><![CDATA[" + content + "]]></Content></xml>";
		return replyAguangSoftTestContentXMLStr;
	}

	/**
	 * 发送小程序客服信息
	 * @param toUserName  oppid
	 * @param description 图文链接消息
	 * @param URL         图文链接消息被点击后跳转的链接
	 * @param thumbUrl	   封面图片的临时cdn链接
	 * @param title       标题
	 * @return
	 * @throws Exception
	 */
	public static void sendWeChatMsg(String toUserName,String description,
			String URL,String thumbUrl,String title) throws Exception {
		
		String param = "<xml><touser><![CDATA[" + toUserName + "]]></touser>"
					+ "<MsgType><![CDATA[link]]></MsgType>"
					+"<link>"
					+"<title><![CDATA["+title+"]]></title>"
					+ "<description><![CDATA["+description+"]]></description>"
					+"<url><![CDATA["+URL+"]]></url>"
					+"<thumb_url><![CDATA["+thumbUrl+"]]></thumb_url>"
					+"</link>"
					+"</xml>";
		HttpRequest.sendPost("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+SystemParamsUtil.getAppToken(), 
				param);
	}

		/**
		 * 向腾讯小程序请求用户的信息
		 * @return openId
		 * @throws Exception 
		 */
		public static JSONObject getUserInfoToWidget(String code,int type) throws Exception{
			String reStr = "";
			JSONObject jsObject = null;
			String url = "https://api.weixin.qq.com/sns/jscode2session";
			String param= "appid="+getAppID(type)+"&"
					+ "secret="+getAppSecret(type)+"&"
					+ "js_code="+code+"&"
					+ "grant_type=authorization_code";
			reStr = HttpRequest.sendGet(url, param);
			jsObject = (JSONObject) JSON.parse(reStr);
			System.out.println("================"+reStr);
			return jsObject;
		}
	
		
	/**
	 * 向腾讯请求用户的信息
	 * @return openId
	 * @throws Exception 
	 */
	public static JSONObject getUserInfoToWeixin(String code,int type) throws Exception{
		String reStr = "";
		JSONObject jsObject = null;
		
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
		String param= "appid="+getAppID(type)+"&"
				+ "secret="+getAppSecret(type)+"&"
				+ "code="+code+"&"
				+ "grant_type=authorization_code";
		reStr = HttpRequest.sendGet(url, param);
		jsObject = (JSONObject) JSON.parse(reStr);
		
		String accessToken = jsObject.getString("access_token");
		String openId = jsObject.getString("openid");
		
//		return openId;
		url = "https://api.weixin.qq.com/sns/userinfo?"
				+ "access_token="+accessToken+"&"
				+ "openid="+openId+"&"
				+ "lang=zh_CN";
		reStr = HttpRequest.sendGet(url, param);
		jsObject = (JSONObject) JSON.parse(reStr);
		return jsObject;
	}
	
	
	/**
	 * 解析腾讯传过来的xml文件
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static Map<String,String> getXMLValueMap(HttpServletRequest request) throws Exception{
		Map<String,String> param = new HashMap<String, String>();
	    InputStream is = request.getInputStream();  
        String pushData = WeiXinUtil.getInfoFromIoStream(is);
 	 	Document document = DocumentHelper.parseText(pushData);  
        Element root = document.getRootElement(); 
		for(@SuppressWarnings("unchecked")
		Iterator<Element> iterator1=root.elementIterator();iterator1.hasNext();){
			root =iterator1.next();
			param.put(root.getName(), root.getText());
		}
		return param;
	}
	
	/**
	 * 生成永久带参数的二维码
	 * @param paramId
	 * @return
	 * @throws Exception
	 */
	public static String getTicket(int paramId,int type) throws Exception{
		String ticket = "";
		String accessToken = getAccessToken(type);
		String paramsJson = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": "+paramId+"}}}"; 
		String responseStr = HttpRequest.sendPost("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+accessToken, paramsJson);
		JSONObject jsObject = (JSONObject) JSON.parse(responseStr);
		ticket = jsObject.getString("ticket");
		return ticket;
	}
	
	/**
	 * 生成零时二维码
	 * @param paramId
	 * @return
	 * @throws Exception
	 */
	public static String getTicketTmp(int paramId,int type) throws Exception{
		String tmpParam = "u"+paramId;
		String ticket = (String) RedisPoolMgr.hashGet("userTicket", paramId+"");
		if(ticket==null||ticket.equals("null")){
			String accessToken = getAccessToken(type);
			JSONObject paramsJsons = new JSONObject();
			paramsJsons.put("expire_seconds", "604800");
			paramsJsons.put("action_name", "QR_STR_SCENE");
			
			JSONObject tmp = new JSONObject();
			tmp.put("scene_str", tmpParam);
			
			JSONObject tmp1 = new JSONObject();
			tmp1.put("scene", tmp);
			
			paramsJsons.put("action_info", tmp1);
			String responseStr = HttpRequest.sendPost("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+accessToken, paramsJsons.toString());
			JSONObject jsObject = (JSONObject) JSON.parse(responseStr);
			System.out.println(jsObject);
			ticket = jsObject.getString("ticket");
			if(ticket!=null&&!ticket.equals("null")){
				RedisPoolMgr.hashSet("userTicket", paramId+"", ticket,60*60*24*29);
			}
		}
		return ticket;
	}
	
	public static String getAppID(int type) throws Exception{
	    String appid = null;
	    if(type==StaticData.userType.COMMON_USER.getType()||
			type==StaticData.userType.CHANNEL_USER.getType()){
		    appid = SystemParamsUtil.getAppIdU();
		}else{
		    appid = SystemParamsUtil.getAppIdD();
		}
	    return appid;
	}
	
	public static String getAppSecret(int type) throws Exception{
	    String sercret = null;
	    if(type==StaticData.userType.COMMON_USER.getType()||
		type==StaticData.userType.CHANNEL_USER.getType()){
		sercret = SystemParamsUtil.getAppSecretU();
	    }else{
		sercret = SystemParamsUtil.getAppSecretD();
	    }
	    return sercret;
	    
	}
}
